/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import entities.Applicant;
import entities.Application;
import entities.Section;
import entities.Staff;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import org.hibernate.HibernateException;
import persistence.GenericDAO;
import persistence.GenericDAOImpl;

/**
 *
 * @author Ant Ongun Kefeli
 */
@Stateless
@LocalBean
public class LoginControllerEJB {

    private Applicant applicant = null;
    private Staff staff = null;
    private GenericDAO<Applicant, Long> appDao = new GenericDAOImpl<Applicant, Long>(Applicant.class);
    private GenericDAO<Staff, Long> staffDao = new GenericDAOImpl<Staff, Long>(Staff.class);

    public Applicant loginApplicant(String email, String password) {
        //for test purposes
//        Applicant ant = new Applicant();
//        ant.setEmail("ant");
//        ant.setPassword("ant");
//        appDao.createOrUpdate(ant);
        applicant = validateUser(email, password);
        if (applicant != null) {
            Application app = applicant.getApplication();
            if (app == null) {
                app = new Application(applicant);
                app.setStatus(Application.Status.UNSUBMITTED);
                app.setEvaluation(Application.Evaluation.NONE);
                appDao.update(applicant);
            }
        }
        return applicant;
    }

    public Staff loginStaff(String email, String password) {
        staff = validateStaff(email, password);
        return staff;
    }

    protected Applicant validateUser(String email, String password) {
        Applicant result = null;
        try {
            List<Applicant> applicants = appDao.findAll();
            for (Applicant app : applicants) {
                if (app.getEmail().equals(email) && app.getPassword().equals(password)) {
                    result = app;
                }
            }
        } catch (HibernateException e) {
            throw e;
        }
        return result;
    }

    protected Staff validateStaff(String email, String password) {
        Staff result = null;
        try {
            List<Staff> staffs = staffDao.findAll();
            for (Staff stafff : staffs) {
                if (stafff.getEmail().equals(email) && stafff.getPassword().equals(password)) {
                    result = stafff;
                }
            }
        } catch (HibernateException e) {
            throw e;
        }
        return result;
    }

    public Applicant getApplicant() {
        return applicant;
    }

    public Staff getStaff() {
        return staff;
    }
}
